/*
Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

*/

class Solution {
public:
    int _search(int *A, int low, int high, int target) {
        if (low > high) return -1;
        int mid = (low+high) >> 1;
        if (A[mid] == target) return mid;
        if (A[low] <= A[mid]) {
            if (A[low] <= target && target < A[mid]) {
                return _search(A, low, mid-1, target);
            } else {
                return _search(A, mid+1, high, target);
            }
        } else if (A[mid] < A[high]) {
            if (A[mid] < target && target <= A[high]) {
                return _search(A, mid+1, high, target);
            } else {
                return _search(A, low, mid-1, target);
            }
        }
        return -1;
    }
    int search(int A[], int n, int target) {
        if (!n) return -1;
        return _search(A, 0, n-1, target);
    }
};

#if 0
class Solution {
public:
    int _search(int *A, int left, int right, int target) {
        if (left > right) return -1;
        int mid = (left + right) >> 1;
        if (A[mid] == target) return mid;
        if (A[left] < A[right]) {
            // regular sorted array
            if (A[mid] < target) {
                return _search(A, mid+1, right, target);
            } else {
                return _search(A, left, mid-1, target);
            }
        } else {
            // rotated sorted array
            if (A[left] <= A[mid]) {
                if (A[left] <= target && target < A[mid]) {
                    return _search(A, left, mid-1, target);
                } else {
                    return _search(A, mid+1, right, target);
                }
            } else if (A[mid] < A[right]) {
                if (A[mid] < target && target <= A[right]) {
                    return _search(A, mid+1, right, target);
                } else {
                    return _search(A, left, mid-1, target);
                }
            }
        }
        return -1;
    }
    int search(int A[], int n, int target) {
        if (!n) return -1;
        return _search(A, 0, n-1, target);
    }
};
#endif
